package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop_srvs/userop_srv/global"
	"mxshop_srvs/userop_srv/model"
	"mxshop_srvs/userop_srv/proto"
)

func (*UserOp) GetAddressList(ctx context.Context, req *proto.AddressRequest) (*proto.AddressListResponse, error) {

	var addressListResponse proto.AddressListResponse
	var addressList []model.Address
	var total int64
	if result := global.DB.Where(&model.Address{User: req.UserId}).Count(&total); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	if result := global.DB.Where(&model.Address{User: req.UserId}).Find(&addressList); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有地址信息")
	}
	addressListResponse.Total = int32(total)
	for _, address := range addressList {
		addressResponse := proto.AddressResponse{
			Id:           address.ID,
			UserId:       address.User,
			Province:     address.Province,
			City:         address.City,
			District:     address.District,
			Address:      address.Address,
			SignerNane:   address.SignerName,
			SignerMobile: address.SignerMobile,
		}
		addressListResponse.Data = append(addressListResponse.Data, &addressResponse)
	}
	return &addressListResponse, nil
}
func (*UserOp) CreateAddress(ctx context.Context, req *proto.AddressRequest) (*proto.AddressResponse, error) {

	address := model.Address{
		User:         req.UserId,
		Province:     req.Province,
		City:         req.City,
		District:     req.District,
		Address:      req.Address,
		SignerName:   req.SignerNane,
		SignerMobile: req.SignerMobile,
	}
	if result := global.DB.Save(&address); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	return &proto.AddressResponse{Id: address.ID}, nil
}
func (*UserOp) DeleteAddress(ctx context.Context, req *proto.AddressRequest) (*emptypb.Empty, error) {
	if result := global.DB.Where("user=? and id=?", req.UserId, req.Id).Delete(&model.Address{}); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "收货地址不存在")
	}
	return &emptypb.Empty{}, nil
}
func (*UserOp) UpdateAddress(ctx context.Context, req *proto.AddressRequest) (*emptypb.Empty, error) {

	var address model.Address
	if result := global.DB.Where("id=? and user=?", req.Id, req.UserId); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "收获地址不存在")
	}
	if req.Province != "" {
		address.Province = req.Province
	}
	if req.City != "" {
		address.City = req.City
	}
	if req.District != "" {
		address.District = req.District
	}
	if req.Address != "" {
		address.Address = req.Address
	}
	if req.SignerNane != "" {
		address.SignerName = req.SignerNane
	}
	if req.SignerMobile != "" {
		address.SignerMobile = req.SignerMobile
	}
	if result := global.DB.Save(&address); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	return &emptypb.Empty{}, nil
}
